<?php

namespace app\classes\controller;

use app\classes\model\AuditionModel;
use app\classes\model\ClassCourseModel;
use app\classes\model\ClassModel;
use app\classes\model\ClassSchoolModel;
use app\classes\model\ClassSeatModel;
use app\classes\model\ClassStudentModel;
use app\classes\model\ClassTeacherModel;
use app\classes\model\StudentLeaveModel;
use app\classroom\model\ClassroomModel;
use app\course\model\CourseModel;
use app\course\model\CoursesCartModel;
use app\course\model\CourseScheduleModel;
use app\educational\model\MessageModel;
use app\student\model\StudentAdjustModel;
use app\student\model\StudentModel;
use app\student\model\StudentVisitModel;
use app\course\validate\ClassesValidate;
use app\portal\model\UserModel;
use app\system\model\SchoolModel;
use  \cmf\controller\AdminBaseController;
use think\Db;
use think\Exception;
use PHPExcel;
use think\Log;

class ClassesController extends AdminBaseController
{
    /*
     * 班级列表
     */
    public function index()
    {
        $param = $this->request->param();
        $limit = config('limit_per_page');
        $where = [
            'c.shop_id' => ['=', $this->admin_shop_id],
            'c.create_time' => ['>=', 0],
            'c.delete_time' => ['eq', 0]
        ];
        $room_model = new ClassModel();

        if (!empty($param['school_id']) && intval($param['school_id']) != 0) {
            //校区
            $where['c.school_id'] = intval($param['school_id']);
        }
        if (!empty($param['classroom_name'])) {
            //教室名称
            $where['cs.name'] = ['like', '%' . trim($param['classroom_name']) . '%'];
        }
        if (!empty($param['teacher_id'])) {
            //班主任
            $where['u.user_login'] = ['like', '%' . trim($param['teacher_id']) . '%'];
        }
        if (!empty($param['name'])) {
            //班级名字
            $where['c.name'] = ['like', '%' . trim($param['name']) . '%'];
        }
        if (!empty($param['schedule'])) {
            //课程进度
            $schedule = trim($param['schedule']);
        }
        $homework_starttime = empty($param['homework_starttime']) ? 0 : strtotime($param['homework_starttime']);
        $homework_endtime   = empty($param['homework_endtime']) ? 0 : strtotime($param['homework_endtime']);
        if (!empty($homework_starttime) && !empty($homework_endtime)) {
            $where['c.start_lesson_time'] = [['>= time', $homework_starttime], ['<= time', $homework_endtime]];
        } else {
            if (!empty($homework_starttime)) {
                $where['c.start_lesson_time'] = ['>= time', $homework_starttime];
            }
            if (!empty($homework_endtime)) {
                $where['c.insert_class_time'] = ['<= time', $homework_endtime];
            }
        }


        //开课，未开课，已结课的状态
        if (!empty($param['class_status'])) {
            if ($param['class_status'] == 1) {
                //未开课状态
                $where['c.class_status'] = 0;
                $this->assign('a', 'selected');
            } else if ($param['class_status'] == 2) {
                //进行中
                $where['c.class_status'] = 1;
                $this->assign('b', 'selected');
            } else if ($param['class_status'] == 3) {
                //已结课
                $where['c.class_status'] = 2;
                $this->assign('c', 'selected');
            }
        }
        //满员未满员
        if (!empty($param['student_status'])) {
            //满员
            if ($param['student_status'] == 1) {
                $data = $room_model->alias('c')->field('c.*,sc.name as campus_name,cs.name as classroom_name,cs.student_nums,u.user_login as user_login,co.course_name,co.course_hour')
                    ->join('school sc', 'c.school_id=sc.id')
                    ->join('class ccc', 'ccc.current_num=c.total_num and ccc.id=c.id')
                    ->join('classroom cs', 'c.classroom_id=cs.id')
                    ->join('course co', 'c.course_id=co.id')
                    ->join('user u', 'c.teacher_id=u.id', $type = 'LEFT')
                    ->where($where)
                    ->order('id', 'desc')
                    ->paginate($limit, false, ['query' => $param]);
            } else if ($param['student_status'] == 2) {
                $data = $room_model->alias('c')->field('c.*,sc.name as campus_name,cs.name as classroom_name,cs.student_nums,u.user_login as user_login,co.course_name,co.course_hour')
                    ->join('school sc', 'c.school_id=sc.id')
                    ->join('class ccc', 'ccc.current_num<c.total_num and ccc.id=c.id')
                    ->join('classroom cs', 'c.classroom_id=cs.id')
                    ->join('course co', 'c.course_id=co.id')
                    ->join('user u', 'c.teacher_id=u.id', $type = 'LEFT')
                    ->where($where)
                    ->order('id', 'desc')
                    ->paginate($limit, false, ['query' => $param]);
            }
        } else {
            $data = $room_model->alias('c')->field('c.*,sc.name as campus_name,cs.name as classroom_name,cs.student_nums,u.user_login as user_login,co.course_name,co.course_hour')
                ->join('school sc', 'c.school_id=sc.id')
                ->join('classroom cs', 'c.classroom_id=cs.id')
                ->join('course co', 'c.course_id=co.id')
                ->join('user u', 'c.teacher_id=u.id', $type = 'LEFT')
                ->where($where)
                ->order('id', 'desc')
                ->paginate($limit, false, ['query' => $param]);
        }


        //所有课程的课程进度和改变课程的状态
        foreach ($data as $k => $v) {
            $arr = $room_model->progress($data[$k]['id']);
            $arr = json_decode($arr, True);
            $data[$k]['progress'] = $arr['progress'];
        }
        $data_scheme=[];
        if(!empty($schedule))
        { //有课程进度 没有对应上就删除
            foreach ($data as $k => $v) {
               if($data[$k]['progress']!=$schedule)
               {
                  unset($data[$k]);
               }
            }
        }

        //获取学校
        $school_mdl = new SchoolModel();
        $school = $school_mdl->getAllSchool($this->admin_shop_id);

        $this->assign('campus', $school);
        $this->assign('param', $param);
        $this->assign('class', $data);
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    //默认添加页面
    public function add()
    {

        //校区的列表
        $school_model = new SchoolModel();
        //$school_tree=$school_model->schoolCategoryTree();
        $school_tree = $school_model->where(['is_school' => '0', 'delete_time' => 0])->select()->toArray();
        //课程的列表和课程类别的分类的删除时候不显示
        $course_model = new CourseModel();
        $course_tree = $course_model->alias('c')->field(['c.course_name', 'c.id', 'c.total_price'])
            ->join('course_category cc', 'c.category_id=cc.id')
            ->where(['cc.delete_time' => 0, 'c.delete_time' => 0])
            ->select()->toArray();
        //老师的列表
        $teacher_model = new UserModel();

        $teacher_tree = Db::name('user')->alias('u')->field('u.*')
            ->join('role_user r', 'r.user_id=u.id')
            ->where(['u.user_status' => 1, 'r.role_id' => 4])
            ->select()
            ->toArray();

        //教室列表
        $classroom_model = new ClassroomModel();
        $classroom_tree = $classroom_model->where(['delete_time' => 0])->field(['id', 'name'])->select()->toArray();
        //是否续班
        $class_model = new ClassModel();
        $class_tree = $class_model->where(['delete_time' => 0])->field(['id', 'name'])->select()->toArray();


        $this->assign('school_tree', $school_tree);
        $this->assign('classroom_tree', $classroom_tree);
        $this->assign('course_tree', $course_tree);
        $this->assign('teacher_tree', $teacher_tree);
        $this->assign('class_tree', $class_tree);


        return $this->fetch();
    }

    //默认添加
    /**
     *
     */
    public function addPost()
    {

        if ($this->request->isPost()) {
            $data = $this->request->param();
            $post = $this->request->post();
            $classes_model = new ClassModel();
            //添加上课时间段为空，删除post['class_time_start']  $post['class_time_end'][0];
            if (count($post['class_time_start']) <= 1 && empty($post['class_time_start'][0])) {
                $post['class_time_start'] = $post['class_time_start'][0];
            }
            if (count($post['class_time_end']) <= 1 && empty($post['class_time_end'][0])) {
                $post['class_time_end'] = $post['class_time_end'][0];
            }
            if (count($post['class_time_start']) > 1 && !empty($post['class_time_start'][0])) {
                $n = date('N', strtotime($post['start_lesson_time']));
                $count_date=count($post['class_start_week']);
                if ($n !=intval($post['class_start_week'][$count_date-1])) {
                    $this->error("选择的开课时间与周".$post['class_start_week'][$count_date-1]."对应不上");
                }
            }


            //一个上课时间段的话，开课的时间对应周几

            $count_date=count($post['class_start_week']);
            if(count($post['class_time_end'])==1){
                $n = date('N', strtotime($post['start_lesson_time']));
                if ($n != intval($post['class_start_week'][0])) {
                    $this->error('选择的开课时间与周几对应不上');
                }
            }
            //多个上课时间，删除空的值，也就是第一个默认是空的
            //多个上课时间段的开课的时间在 周-~周日
            if (count($post['class_time_start']) > 1 && empty($post['class_time_start'][0])) {
                unset($post['class_start_week'][0]);
                unset($post['class_time_start'][0]);
                unset($post['class_time_end'][0]);
                $n = date('N', strtotime($post['start_lesson_time']));
                $count_date=count($post['class_start_week']);
                if ($n !=intval($post['class_start_week'][$count_date])) {
                    $this->error("选择的开课时间与周".$post['class_start_week'][$count_date]."对应不上");
                }
            }

            //判断开课时间和周几对应起来
            if (date('N', strtotime($post['start_lesson_time']))) {
                $post['class_start_week'] = $post['class_start_week'];
            }
            //验证开课的时间必须大于报名的时间
            $start_lesson_time = strtotime($post['start_lesson_time']);
            $signup_start = strtotime($post['signup_start']);
            if ($start_lesson_time <= $signup_start) {
                $this->error('开课的时间怎么小于报名的时间呢');

            }
            //验证信息
            $result = $this->validate($post, 'Classes');
            if ($result !== true) {
                $this->error($result);
            }
            $post['class_start_week'] = implode(',', $post['class_start_week']);
            $post['class_time_start'] = implode(',', $post['class_time_start']);
            $post['class_time_end'] = implode(',', $post['class_time_end']);
            $post['start_lesson_time'] = strtotime($post['start_lesson_time']);
            $post['signup_start'] = strtotime($post['signup_start']);
            //如果没有续班，删除$post['class'] $post['shcool']
            if (!isset($post['is_class'])) {
                unset($post['enable_class']);
                unset($post['enable_school']);
            } else {
                if (empty($post['enable_class']) || empty($post['enable_school'])) {
                    //选择选班，验证选择学校
                    $this->error('没有选择续班的班级和校区');
                }
                //续班的学校和班级的记录
                $post['enable_class_ids'] = $post['enable_class'] . ',' . $post['enable_school'];
                unset($post['enable_class']);
                unset($post['enable_school']);
            }
            $classroom_model = new ClassroomModel();
            //教室列表的总人数
            $total_num = $classroom_model->where(['id' => $post['classroom_id']])->value('student_nums');
            //保留座位数据和学生作为数据
            $reserved_seats = $post['reserved_seats'];
            if (!empty($reserved_seats)) {
                $reserved_seats_num = count(explode(',', $reserved_seats));
                $post['total_num'] = $total_num - $reserved_seats_num;
            } else {
                $post['total_num'] = $total_num;
            }
            //删除后添加班级_课程表，班级_老师表，班级_校区表
            unset($post['student_seat']);
            unset($post['reserved_seats']);
            //判断课程的名字是否存在
            $total = $classes_model->where('delete_time', '=', 0)
                ->where(['name' => trim($post['name'])])->count();
            if (isset($total) && $total >= 1) {
                $this->error('该班级已存在');
            }
            //班级——学校的数据
            $class_school_data = [];
            $class_school_data['school_id'] = $post['school_id'];

            //班级——老师的数据
            $class_teacher_data = [];
            $class_teacher_data['user_id'] = $post['teacher_id'];

            //班级——课程的数据
            $class_course_data = [];
            $class_course_data['course_id'] = $post['course_id'];

            //构建座位表
            $seat = [];
            //create_time
            $create_time = time();
            $post['create_time'] = $create_time;
            //开启事物
            Db::startTrans();
            try {
                $classes_id = $classes_model->insertGetId($post);
                $room_model=new ClassModel();
                $room_model->progress($classes_id);

                //座位表信息
                //student_id==0是保留座位的信息，添加时候可以设置保留座位
                $seat['student_id'] = 0;
                $seat['classes_id'] = $classes_id;
                $seat['course_id']= $post['course_id'];

                $seat['classroom_id'] = $post['classroom_id'];
                $seat['create_time'] = $create_time;

                //班级——学校的数据
                $class_school_data['class_id'] = $classes_id;
                $class_school_data['create_time'] = $create_time;

                //班级——老师的数据
                $class_teacher_data['class_id'] = $classes_id;
                $class_teacher_data['create_time'] = $create_time;

                //班级——课程的数据
                $class_course_data['class_id'] = $classes_id;
                $class_course_data['create_time'] = $create_time;

                //判断保留座位是否为空
                if (!empty($reserved_seats)) {
                    $seat['reserved_seats'] = serialize($reserved_seats);
                } else {
                    $seat['reserved_seats'] = '';
                }

                $class_seat_model = new ClassSeatModel();
                $class_school_model = new ClassSchoolModel();
                $class_course_model = new ClassCourseModel();
                $class_teacher_model = new ClassTeacherModel();

                //修改教室模板中--班级字段————班级数量
                $class_nums = $classes_model->where(['classroom_id' => $post['classroom_id'], 'delete_time' => 0])->count();
                $result_classroom = $classroom_model->where('id', $post['classroom_id'])->update(['class_nums' => $class_nums]);

                $class_seat_model->insert($seat);
                $class_school_model->insert($class_school_data);
                $class_course_model->insert($class_course_data);
                $class_teacher_model->insert($class_teacher_data);

                //排课的表
                $course_schema = $classes_model->getCourseTime($class_id = $classes_id, $course_start = 0, $course_hour = 0, $shop_id = 1);

                foreach ($course_schema as $k => $v) {
                    //课程计划
                    $data_schema = [];
                    $data_schema['class_id'] = $classes_id;
                    $data_schema['classroom_id'] = $post['classroom_id'];
                    $data_schema['teacher_id'] = $post['teacher_id'];
                    $data_schema['date'] = strtotime($v['date']);
                    $data_schema['start_time'] = $v['start_time'];
                    $data_schema['end_time'] = $v['end_time'];
                    $data_schema['schedule'] = $v['schedule'];
                    $data_schema['week'] = $v['cur_week'];
                    Db::name('course_schedule')->insert($data_schema);

                }
                Db::commit();

                //记录日志
                $seat_id = $class_seat_model->getLastInsID(); //座位的id
                $id = $classes_id . ',' . $seat_id;  //pk记住
                $pk = $id; //主键
                $table = 'class';//数据表名
                $content = lang('ADD_CLASS', ['name' => $post['name']]);
                do_log($content, $pk, $table, time());

                $this->success('添加成功', url('classes/index'));
                // 如果出错了就去掉\,和删除一样
            } catch (Exception $e) {
                $this->error('添加失败');
                Db::rollback();
            }

        }
    }

    /*
     * 班级edit
     */
    public function edit()
    {

        //$id
        $id = $this->request->param('id');
        $classModel = new ClassModel();
        $classSeatModel = new ClassSeatModel();
        $classStudentModel = new ClassStudentModel();
        $course_model = new CourseModel();
        $teacher_model = new UserModel();
        $is_and_class = $classModel->where('id', $id)->value('is_and_class');
        //校区的列表
        $school_model = new SchoolModel();
        $school_tree = $school_model->where(['is_school' => '0', 'delete_time' => 0])->select()->toArray();
        //课程的列表
        $course_tree = $course_model->alias('c')->field(['c.course_name', 'c.id', 'c.total_price'])
            ->join('course_category cc', 'c.category_id=cc.id')
            ->where(['cc.delete_time' => 0, 'c.delete_time' => 0])
            ->select()->toArray();
        //老师的列表

        $teacher_tree = Db::name('user')->alias('u')->field('u.*')
            ->join('role_user r', 'r.user_id=u.id')
            ->where(['u.user_status' => 1, 'r.role_id' => 4])
            ->select()
            ->toArray();
        //教室列表
        $classroom_model = new ClassroomModel();
        $classroom_tree = $classroom_model->where(['delete_time' => 0])->field(['id', 'name'])->select()->toArray();
        //续班列表
        $class_model = new ClassModel();
        $class_tree = $class_model->where(['delete_time' => 0])->field(['id', 'name'])->select()->toArray();


        $data = $classModel->alias('c')->field('c.*,sc.name as campus_name,cs.name as classroom_name,cs.student_nums,u.user_login as user_login ,co.course_name')
            ->join('school sc', 'c.school_id=sc.id')
            ->join('classroom cs', 'c.classroom_id=cs.id')
            ->join('course co', 'c.course_id=co.id')
            ->join('user u', 'c.teacher_id=u.id', $type = 'LEFT')
            ->where('c.id', $id)->find();
        $this->assign('course_tree', $course_tree);
        //多个开课时间
        $class_start = [];
        $class_start_week = explode(',', $data['class_start_week']);
        $class_time_start = explode(',', $data['class_time_start']);
        $class_time_end = explode(',', $data['class_time_end']);
        for ($i = 0; $i < count($class_start_week); $i++) {
            $class_start[$i]['class_start_week'] = $class_start_week[$i];
            $class_start[$i]['class_time_start'] = $class_time_start[$i];
            $class_start[$i]['class_time_end'] = $class_time_end[$i];

        }
        //判断续班 is_class不是空的话

        $enable_class_shool = 0;
        $enable_class_all = 0;
        $enable_class_class = 0;
        $enable_class_all = [];

        if (!empty($data['is_class'])) {
            //是否续班 校区
            $enable_class = explode(',', $data['enable_class_ids']);
            $enable_class_shool = intval($enable_class[1]);
            $enable_class_class = intval($enable_class[0]);
            $course_id = $class_model->where('id', $id)->value('course_id');
            //续班班级的查询
            $enable_class_all = Db::name('class')->where(['delete_time' => 0, 'school_id' => $enable_class_shool, 'course_id' => $course_id, 'is_and_class' => 0, 'class_status' => 0])->select()->toArray();
        } else {
            $enable_class_shool = $class_model->where('id', $id)->value('school_id');
            $course_id = $class_model->where('id', $id)->value('course_id');

            //续班班级的查询
            $enable_class_all = Db::name('class')->where(['delete_time' => 0, 'school_id' => $enable_class_shool, 'course_id' => $course_id, 'is_and_class' => 0, 'class_status' => 0])->select()->toArray();
        }
        //默认的教室
        $classroom = $classroom_model->where(['delete_time' => 0, 'id' => $data['classroom_id']])->select()->toArray();
        //chase添加
        $classseat = $classSeatModel->where(['classes_id'=>$id,'delete_time'=>0])->select()->toArray();

        if (!empty($classroom[0]['vip'])) {
            $classroom[0]['vip'] = unserialize($classroom[0]['vip']);
        }
        if (!empty($classroom[0]['aisle'])) {
            $classroom[0]['aisle'] = unserialize($classroom[0]['aisle']);
        }
        //查询有座位的学生的姓名,座位
        $classseat_stu = $classSeatModel->alias('cs')
            ->where(['cs.classes_id' => $id, 'cs.delete_time' => 0])
            ->join('student s', 'cs.student_id=s.id')
            ->field('cs.*,s.code,s.name')
            ->select()
            ->toArray();

        //查询保留的座位
        $classseat_res = $classSeatModel
            ->where('classes_id', $id)
            ->where('reserved_seats', '<>', '')
            ->select()
            ->toArray();

        //查询并班的学生ID和信息
        $classstudent_bing = $classStudentModel->alias('cs')
            ->where('class_id', $id)
            ->where('status', '1')
            ->join('student s', 'cs.student_id=s.id')
            ->field('cs.*,s.code,s.name')
            ->select()
            ->toArray();
        foreach ($classseat_stu as &$v) {
            if (!empty($v['student_seat'])) {
                $v['student_seat'] = unserialize($v['student_seat']);
            }
        }

        if (!empty($classseat_res)) {
            $classseat_res[0]['reserved_seats'] = unserialize($classseat_res[0]['reserved_seats']);
        }

        //传输对象给js处理
        $this->assign('classseat_stu', json_encode($classseat_stu));
        $this->assign('classseat_res', json_encode($classseat_res));
        $this->assign('classroomJS', json_encode($classroom));
        $this->assign('classstudent_bing', json_encode($classstudent_bing));
        $this->assign('classroom', $classroom);
        $this->assign('enable_class_shool', $enable_class_shool);
        $this->assign('enable_class_all', $enable_class_all);
        $this->assign('enable_class_class', $enable_class_class);
        $this->assign('class_start', $class_start);
        $this->assign('data', $data);
        $this->assign('is_and_class', $is_and_class);

        $this->assign('school_tree', $school_tree);
        $this->assign('classroom_tree', $classroom_tree);
        $this->assign('course_tree', $course_tree);
        $this->assign('teacher_tree', $teacher_tree);
        $this->assign('class_tree', $class_tree);


        return $this->fetch();


    }


    /**
     *班级的编辑
     * 并班的编辑座位，后台给调整座位
     * 转班的调整座位
     */
    public function editPost()
    {

        if ($this->request->isPost()) {
            $data = $this->request->param();
            $post = $this->request->post();
            $id = $data['id'];
            if (!empty($data['student_bing'])) {
                unset($post['student_bing']);
            }
            if (empty($data['is_listen'])) {
                $post['is_listen'] = 0;
            }
            //验证课判断
            if ($data['course_id'] == 0) {
                $this->error('关联课程没有选择');
            }
            //验证授课老师
            if ($data['teacher_id'] == 0) {
                $this->error('授课老师没有选择');
            }
            $classes_model = new ClassModel();
            $classroom_model = new ClassroomModel();
            $class_seat_model = new ClassSeatModel();
            $class_student_model = new ClassStudentModel();
            $class_school_model = new ClassSchoolModel();
            $class_course_model = new ClassCourseModel();
            $class_teacher_model = new ClassTeacherModel();

            //多个上课时间的处理
            if (count($post['class_time_start']) > 1 && $post['class_time_start'][0] == '') {
                unset($post['class_start_week'][0]);
                unset($post['class_time_start'][0]);
                unset($post['class_time_end'][0]);
                $n = date('N', strtotime($post['start_lesson_time']));

                $count_date=count($post['class_start_week']);
                if ($n !=intval($post['class_start_week'][$count_date])) {
                    $this->error("选择的开课时间与周".$post['class_start_week'][$count_date]."对应不上");
                }
            } else if (empty($post['class_time_start'][0]) || empty($post['class_time_end'][0])) {
                $this->error('上课开始时段或者上课结束时段不能为空');
            }
            if (count($post['class_time_start']) > 1 && !empty($post['class_time_start'][0])) {
                $n = date('N', strtotime($post['start_lesson_time']));
                $count_date = count($post['class_start_week']);
                if ($n != intval($post['class_start_week'][$count_date - 1])) {
                    $this->error("选择的开课时间与周" . $post['class_start_week'][$count_date-1] . "对应不上");
                }
            }
            //验证开课的时间必须大于报名的时间
            $start_lesson_time = strtotime($post['start_lesson_time']);
            $signup_start = strtotime($post['signup_start']);
            if ($start_lesson_time <= $signup_start) {
                $this->error('开课的时间怎么小于报名的时间呢');

            }
            //验证
            $result = $this->validate($post, 'ClassesEdit');
            if ($result !== true) {
                $this->error($result);
            }
            $classroom_id = $classes_model->where('id', $id)->value('classroom_id');
            $post['class_start_week'] = implode(',', $post['class_start_week']);
            $post['class_time_start'] = implode(',', $post['class_time_start']);
            $post['class_time_end'] = implode(',', $post['class_time_end']);
            $post['start_lesson_time'] = strtotime($post['start_lesson_time']);
            $post['signup_start'] = strtotime($post['signup_start']);
            //是否续班的处理
            if (!isset($post['is_class'])) {
                unset($post['enable_class']);
                //假如本身存在续班，想取消的话
                $enable_class_ids = $classes_model->where(['id' => $id])->value('enable_class_ids');
                if (!empty($enable_class_ids)) {
                    $classes_model->where(['id' => $id])->update(['enable_class_ids' => '', 'is_class' => 0]);
                }
            } else {
                if (empty($post['enable_class'])) {
                    $this->error('没有选择续班的班级');
                }
                $school_id = $classes_model->where('id', $id)->value('school_id');
                $post['enable_class_ids'] = $post['enable_class'] . ',' . $school_id;


                if($id==$post['enable_class'])
                {
                    $this->error('不能续报本班');
                }

                //续班 a-b b-a
                $xu_class_school=Db::name('class')->where(['id'=>$post['enable_class']])->value('enable_class_ids');
                if(!empty($xu_class_school))
                {
                    $xu_id=explode(',',$xu_class_school)[0];
                    if($xu_id==$id)
                    {
                        $this->error('不能续报本班A-B,B-A,两个班互相续班');
                    }
                }
                unset($post['enable_class']);

            }
            //保留座位数据和学生作为数据
            $reserved_seats = $post['reserved_seats'];
            $classroom_id = $classes_model->where(['id' => $id])->value('classroom_id');
            if (!empty($reserved_seats)) {
                $reserved_seats_num = count(explode(',', $reserved_seats));

                $total_num = $classroom_model->where(['id' => $classroom_id])->value('student_nums');
                $num = $total_num - $reserved_seats_num;
                $post['total_num'] = $num;
            }
            //重新更新班级的现有人数
            $student_seat = $post['student_seat'];
            unset($post['student_seat']);
            unset($post['reserved_seats']);

            $total = $classes_model->where('delete_time', '=', 0)
                ->where(['name' => trim($post['name'])])->where('id', '<>', $post['id'])->count();

            if (isset($total) && $total >= 1) {
                $this->error('该班级已存在');
            }

//            $x = $this->request->param('student_seat');
//            $x = explode(",", $x);
//            dump($reserved_seats);
//            dump($x);
//            dump($student_seat);
//            for ($i = 0; $i < count($x); $i = $i + 2) {
//                $student_seat = serialize($x[$i]);
//                $status = $class_student_model->where(['student_id' => $x[$i + 1], 'class_id' => $id])->value('status');
//                dump($status);
//            }
//            exit();
            //保留座位是否存在座位表中
           $is_bao=$class_seat_model->where(['student_id' => 0, 'classes_id' => intval($id)])->find();
            if(empty($is_bao))
            {
                //student_id==0是保留座位的信息，添加时候可以设置保留座位
                $seat=[];
                $seat['student_id'] = 0;
                $seat['classes_id'] = $id;
                $seat['classroom_id'] = $classroom_id;
                $seat['create_time'] = time();
                $class_seat_model->insert($seat);
            }
            Db::startTrans();
            try {
                $update_time = time();
                $post['update_time'] = $update_time;
                $classes_model->isUpdate(true)->allowField(true)->save($post, ['id' => $id]);
                $class_date = $classes_model->where(['id' => $id])->find();
                $teacher_id = $class_date['teacher_id'];
                $course_id = $class_date['course_id'];

                //添加成功后，添加座位信息,学生最为空
                if (!empty($reserved_seats) && empty($student_seat)) {
                    $reserved_seats = serialize($reserved_seats);

                    $class_seat_model->where(['student_id' => 0, 'classes_id' => intval($id)])->update(['update_time' => $update_time, 'reserved_seats' => $reserved_seats]);
                }
                //添加成功后，添加学生为空，保留座位为空
                if (!empty($student_seat) && empty($reserved_seats)) {
                    $student_ids = [];
                    $x = $this->request->param('student_seat');
                    $x = explode(",", $x);
                    for ($i = 0; $i < count($x); $i = $i + 2) {
                        $student_seat = serialize($x[$i]);
                        $status = $class_student_model->where(['student_id' => $x[$i + 1], 'class_id' => $id])->value('status');
                        if ($status == 1) {
                            $insert = [];
                            $insert['student_id'] = $x[$i + 1];
                            $insert['classes_id'] = $id;
                            $insert['classroom_id'] = $class_seat_model->where(['student_id' => 0, 'classes_id' => $id])->value('classroom_id');
                            $insert['student_seat'] = $student_seat;
                            $insert['create_time'] = time();
                            $class_seat_model->insert($insert);
                            $class_student_model->where(['student_id' => $x[$i + 1], 'class_id' => $id])->update(['status' => 0]);
                        } else {
                            $class_seat_model->where(['student_id' => $x[$i + 1], 'classes_id' => $id])->update(['update_time' => time(), 'student_seat' => $student_seat]);
                        }


                    }
                    $current_num = $class_student_model->where(['class_id' => $id,'delete_time'=>0])
                        ->where('student_id', '<>', 0)->count(); //改变班级人数
                    $classes_model->where(['id' => $id])->update(['update_time' => time(), 'current_num' => $current_num]);

                    //记录日志
                    if (!empty($student_ids)) {
                        $name = '';
                        $classname = Db::name('class')->where(['id' => $id])->value('name');
                        $pk = $id; //主键
                        $table = 'class';//数据表名
                        foreach ($student_ids as $v) {
                            $old_class_id = Db::name('class_student')->where(['student_id' => $v, 'class_id' => $id])->value('old_class_id');
                            $name = Db::name('class')->where(['id' => $old_class_id])->value('name');

                            $content = lang('DISTRIBUTE_STUDENT_STUDENT', ['oldname' => $name, 'newname' => $classname]);
                            do_log_student_active($content, $pk, $table, time(), $v);
                        }
                    }

                }
                //座位不为空和学生不为空
                //添加成功后，添加学生为空，保留座位为空
                if (!empty($student_seat) && empty(!$reserved_seats)) {

                    //判断学生是否是并班的学生，是的话
                    $reserved_seats = serialize($reserved_seats);
                    $class_seat_model->where(['student_id' => 0, 'classes_id' => intval($id)])->update(['update_time' => $update_time, 'reserved_seats' => $reserved_seats]);

                    $student_ids = [];
                    $x = $this->request->param('student_seat');
                    $x = explode(",", $x);
                    for ($i = 0; $i < count($x); $i = $i + 2) {
                        $student_seat = serialize($x[$i]);
                        $status = $class_student_model->where(['student_id' => $x[$i + 1], 'class_id' => $id])->value('status');
                        if ($status == 1) {
                            $insert = [];
                            $insert['student_id'] = $x[$i + 1];
                            $insert['classes_id'] = $id;
                            $insert['classroom_id'] = $class_seat_model->where(['student_id' => 0, 'classes_id' => $id])->value('classroom_id');
                            $insert['student_seat'] = $student_seat;
                            $insert['create_time'] = time();
                            $class_student_model->where(['student_id' => $x[$i + 1], 'class_id' => $id])->update(['status' => 0]);
                            $student_ids[] = $x[$i + 1];
                            $class_seat_model->insert($insert);
                        } else {
                            $class_seat_model->where(['student_id' => $x[$i + 1], 'classes_id' => $id])->update(['update_time' => time(), 'student_seat' => $student_seat]);
                        }


                    }
                    $current_num = $class_student_model->where(['class_id' => $id])
                        ->where(['delete_time'=>0])->count();
                    $classes_model->where(['id' => $id])->update(['update_time' => time(), 'current_num' => $current_num]);

                    //记录日志
                    if (!empty($student_ids)) {
                        $name = '';
                        $classname = Db::name('class')->where(['id' => $id])->value('name');
                        $pk = $id; //主键
                        $table = 'class';//数据表名
                        foreach ($student_ids as $v) {
                            $old_class_id = Db::name('class_student')->where(['student_id' => $v, 'class_id' => $id])->value('old_class_id');
                            $name = Db::name('class')->where(['id' => $old_class_id])->value('name');

                            $content = lang('DISTRIBUTE_STUDENT_STUDENT', ['oldname' => $name, 'newname' => $classname]);
                            do_log_student_active($content, $pk, $table, time(), $v);
                        }
                    }

                }



                //班级——老师表
                $class_teacher_model->where(['user_id' => $teacher_id, 'class_id' => $id])->update(['update_time' => $update_time, 'user_id' => $data['teacher_id']]);
                //班级--课程表
                $class_course_model->where(['course_id' => $course_id, 'class_id' => $id])->update(['update_time' => $update_time, 'course_id' => $data['course_id']]);


                $course_schema = $classes_model->getCourseTime($class_id = $id, $course_start = 0, $course_hour = 0, $shop_id = 1);
                $teacher_id = $classes_model->where(['id' => $class_id])->value('teacher_id');
                $res = Db::name('course_schedule')->where('class_id', $class_id)->delete();

                foreach ($course_schema as $k => $v) {
                    //课程计划
                    $data_schema = [];
                    $data_schema['class_id'] = $id;
                    $data_schema['teacher_id'] = $teacher_id;
                    $data_schema['classroom_id'] = $v['classroom_id'];
                    $data_schema['date'] = strtotime($v['date']);
                    $data_schema['start_time'] = $v['start_time'];
                    $data_schema['end_time'] = $v['end_time'];
                    $data_schema['schedule'] = $v['schedule'];
                    $data_schema['week'] = $v['cur_week'];
                    Db::name('course_schedule')->insert($data_schema);
                }
                $room_model=new ClassModel();
                $room_model->progress($id);

                Db::commit();

                //记录日志
                $pk = $id; //主键
                $table = 'class';//数据表名
                $content = lang('EDIT_CLASS', ['name' => $post['name']]);
                do_log($content, $pk, $table, time());

                $this->success('编辑班级成功', url('classes/index'));
//                //如果出错了就去掉\,和删除一样
            } catch (Exception $e) {
                Db::rollback();
            $this->error('编辑班级失败', url('classes/index'));

            }

        }
    }

    /*
     * 班级的删除
     */
    public function delete()
    {
        $ids = $this->request->param('ids/a');
        $id = $this->request->param('id', 0, 'intval');

        $class_model = new ClassModel();
        $classroom_model = new ClassroomModel();
        $class_seat_model = new ClassSeatModel();
        $class_student_model = new ClassStudentModel();
        $class_school_model = new ClassSchoolModel();
        $class_course_model = new ClassCourseModel();
        $class_teacher_model = new ClassTeacherModel();
        $course_schedule=new CourseScheduleModel();

        $count = $class_student_model->where(['class_id' => $id,'delete_time'=>0])->where('student_id', '<>', 0)->count('student_id');
        $name = $class_model->where(['id' => $id])->value('name');

        if ($count > 0) {
            $this->error('有学生不能删除');
        }
        if (!is_array($ids)) {
            $id = $this->request->param('id', 0, 'intval');
            $count = $class_seat_model->where('classes_id', $id)->count('student_seat');
            $class_date = $class_model->where(['id' => $id])->find();
            $teacher_id = $class_date['teacher_id'];
            $course_id = $class_date['course_id'];
            $school_id = $class_date['school_id'];

            //开始事物
            Db::startTrans();
            try {
                $delete_time = time();
                $res = $class_model->where('id', intval($id))->update(['delete_time' => $delete_time]);
                //改变教室的个数
                $classroom_id = $class_model->where('id', intval($id))->value('classroom_id');
                $count = $class_model->where(['classroom_id' => $classroom_id, 'delete_time' => 0])->count();
                $result = $classroom_model->where('id', $classroom_id)->update(['class_nums' => $count]);
                $resul = $class_seat_model->where('classes_id', $id)->update(['delete_time' => $delete_time]);

                //班级——老师表
                $class_teacher_model->where(['user_id' => $teacher_id, 'class_id' => $id])->update(['delete_time' => $delete_time]);
                //班级--课程表
                $class_course_model->where(['course_id' => $course_id, 'class_id' => $id])->update(['delete_time' => $delete_time]);
                //班级--校区表
                $class_school_model->where(['school_id' => $school_id, 'class_id' => $id])->update(['delete_time' => $delete_time]);

                //删除排课
                $course_schedule->where(['class_id'=>$id])->delete();

                Db::commit();
                //记录日志
                $ids = $id;  //pk记住
                $pk = $ids; //主键
                $table = 'class';//数据表名
                $content = lang('DELETE_CLASS', ['name' => $name]);
                do_log($content, $pk, $table, time());
                $this->success('删除成功');
            } catch (Exception $e) {
                Db::rollback();
                $this->error('删除失败');
            }
        } else {
            $cur_time = time();
            if (is_array($ids)) {
                //批量删除
                Db::startTrans();
                try {
                    $class_model->where(['id' => ['in', $ids]])->update(['delete_time' => $cur_time]);
                    $name_all = '';
                    foreach ($ids as $id) {
                        //改变教室的个数
                        $classroom_id = $class_model->where('id', intval($id))->value('classroom_id');
                        $count = $class_student_model->where(['class_id' => $id])->where('student_id', '<>', 0)->count('student_id');
                        if ($count > 0) {
                            $this->error('有学生不能删除');
                        }
                        $class_date = $class_model->where(['id' => $id])->find();
                        $name_all .= $class_date['name'] . ', ';

                        $teacher_id = $class_date['teacher_id'];
                        $course_id = $class_date['course_id'];
                        $school_id = $class_date['school_id'];

                        $count = $class_model->where(['classroom_id' => $classroom_id, 'delete_time' => 0])->count();
                        $result = $classroom_model->where('id', $classroom_id)->update(['class_nums' => $count]);
                        $resul = $class_seat_model->where('classes_id', $id)->update(['delete_time' => $cur_time]);

                        //班级——老师表
                        $class_teacher_model->where(['user_id' => $teacher_id, 'class_id' => $id])->update(['delete_time' => $cur_time]);
                        //班级--课程表
                        $class_course_model->where(['course_id' => $course_id, 'class_id' => $id])->update(['delete_time' => $cur_time]);
                        //班级--校区表
                        $class_school_model->where(['school_id' => $school_id, 'class_id' => $id])->update(['delete_time' => $cur_time]);
                    }
                    $pk = implode(",", $ids); //主键
                    $table = 'class';//数据表名
                    $content = lang('DELETE_CLASS', ['name' => $name_all]);
                    do_log($content, $pk, $table, time());
                    Db::commit();
                    $this->success('删除成功');
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error('删除失败');
                }
            }
        }

    }

    /*
    * 班级的的并班的显示页面
    */
    public function andClass()
    {
        $id = $this->request->param('ids');
        $class_model = new ClassModel();
        $sing_data = $class_model->where('id', $id)->find();
        $school_id = $sing_data['school_id'];
        $course_id = $sing_data['course_id'];
        $name = $class_model->where('id', $id)->value('name');
        //同课程，同校区，没有满员的,上课正在进行中或者没有开班的,没有并过班的
        $data = $class_model
            ->where('id', '<>', $id)  //不是自己
            ->where('class_status','<>','2') //没有结课
            ->where(['delete_time' => 0, 'school_id' => $school_id, 'course_id' => $course_id, 'is_and_class' => 0])
            ->select()->toArray();
        $this->assign('data', $data);
        $this->assign('data1',json_encode($data));
        $this->assign('name', $name);
        $this->assign('original_class_id', $id);

        return json_encode($data);
    }

    /*
    * 班级的的并班ancClassPost()
    */
    public function addClassPost()
    {

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (empty($data['and_class'])) {
                $this->error('没有选择班级');
            }
            $original_class_id = $this->request->post('original_class_id');
            $class_student = Db::name('class_student')->where(['class_id' => $original_class_id, 'delete_time' => 0])->column('id');
            $class_student_status = Db::name('class_student')->where(['class_id' => $original_class_id, 'delete_time' => 0])->column('status');
            foreach ($class_student_status as $v) {
                if (intval($v == 1)) {
                    return 1;
                    $this->error('有学生在班级没有选座');
                }
            }
            $class_model = new ClassModel();
            $classroom_model = new ClassroomModel();
            $class_seat_model = new ClassSeatModel();
            $class_student = Db::name('class_student')->where(['class_id' => $original_class_id, 'delete_time' => 0])->count('id');
            //如果有学生没有选座选座
            $class_student_status = Db::name('class_student')->where(['class_id' => $original_class_id, 'delete_time' => 0])->column('status');
            if (empty($class_student)) {
                return 2;
                return $this->error('此班级没有学生');
            }
            if (count($data['and_class']) == 1) {
                $pre_class_ids = $data['and_class'][0];
                $newname = $class_model->where(['id' => $pre_class_ids])->value('name');
            } else if (count($data['and_class']) > 1) {
                $newname = '';
                $pre_class_ids = implode(',', $data['and_class']);
                foreach ($data['and_class'] as $k => $v) {
                    $newname .= $class_model->where(['id' => intval($v)])->value('name') . '班级 --';
                }

            } else {
                $pre_class_ids = 0;
            }
            Db::startTrans();
            try {
                //删除原来班级
                $res = $class_model->where('id', intval($original_class_id))->update(['is_and_class' => 1]);
                $oldname = $class_model->where('id', intval($original_class_id))->value('name');

                //改变教室的个数
                $classroom_id = $class_model->where('id', intval($original_class_id))->value('classroom_id');
                $count = $class_model->where(['classroom_id' => $classroom_id, 'is_and_class' => 0])->count();
                $result = $classroom_model->where('id', $classroom_id)->update(['class_nums' => $count]);
                //删除座位表的个人座位信息
//                $resul = $class_seat_model->where('classes_id', $original_class_id)->update(['delete_time' => time()]);
                //原班级的所有的学生
                $class_student = Db::name('class_student')->where(['class_id' => intval($original_class_id), 'delete_time' => 0])->column('id');
                Db::name('class_student')->where(['id' => ['in', $class_student]])->update(['pre_class_ids' => strval($pre_class_ids), 'old_class_id' => $original_class_id, 'status' => 1, 'student_status' => 1]);
                Db::commit();

                //记录日志
                $ids = $original_class_id; //pk记住
                $pk = $ids; //主键
                $table = 'class&class_seat';//数据表名
                $content = lang('MERGE_CLASS', ['oldname' => $oldname, 'newname' => $newname]);
                do_log($content, $pk, $table, time());

              return 3;
            } catch (Exception $e) {
                Db::rollback();
                return 4;
            }
        }
    }

    /*
  * 班级详情
  */
    public function view()
    {
        $param = $this->request->param();
        $id = $param['id'];

        //如果是并班的班级的详情页
        $is_and_class = Db::name('class')->alias('cs')->where('cs.id', $id)->value('is_and_class');

        $class_name=Db::name('class')->alias('cs')->where('cs.id', $id)->value('name');

        if (!empty($is_and_class)) {
            //并班的班级
            $data = Db::name('class_student')->alias('cs')->field('t.id tid,t.birthday,t.school_name,t.code tcode,t.name tname,t.gender tgender,t.parent_name,t.mobile,cs.id,cs.status csstatus,cs.insert_class_time,cs.old_class_id,cs.student_status,cs.class_id,cs.pre_class_ids,cs.id csid,cs.old_class_id,c.name cname')
                ->join('class c', 'c.id=cs.class_id')
                ->join('student t', 't.id=cs.student_id')
                ->where('cs.old_class_id', $id)
                ->where(['cs.delete_time'=>0])
                ->order("convert(`tname` USING gbk) COLLATE gbk_chinese_ci")
                ->select()->toArray();
            $is_and_class=1;
            $this->assign('is_and_class',$is_and_class);
        } else {
            //没有并班的班级
            $data = Db::name('class_student')->alias('cs')->field('t.id tid,t.school_name,t.birthday,t.code tcode,t.name tname,t.gender tgender,t.parent_name,t.mobile,cs.id,cs.insert_class_time ,cs.status csstatus,cs.old_class_id,cs.class_id,cs.id,cs.student_status,cs.pre_class_ids,cs.id csid,cs.old_class_id,c.name cname,c.is_and_class')
                ->join('class c', 'c.id=cs.class_id')
                ->join('student t', 't.id=cs.student_id')
                ->where(['cs.class_id' => $id])
                ->where(['cs.delete_time'=>0])
                ->where(['c.is_and_class' => 0])
                ->order("convert(`tname` USING gbk) COLLATE gbk_chinese_ci")
                ->select()->toArray();
            //转班的数据学生
            $change_data = Db::name('class_student')->alias('cs')->field('t.id tid,t.code tcode,t.birthday,t.school_name,t.name tname,t.gender tgender,t.parent_name,t.mobile,cs.id,cs.status csstatus,cs.insert_class_time,cs.old_class_id,cs.student_status,cs.class_id,cs.pre_class_ids,cs.id csid,cs.old_class_id,c.name cname,c.is_and_class')
                ->join('class c', 'c.id=cs.class_id')
                ->join('student t', 't.id=cs.student_id')
                ->where('cs.old_class_id', $id)
                ->where(['cs.delete_time'=>0])
                ->order("convert(`tname` USING gbk) COLLATE gbk_chinese_ci")
                ->select()->toArray();


            $count = count($data);
            $j = 0;

            foreach ($change_data as $k => $v) {

                if ($v['student_status'] == 2 && !empty($v['old_class_id'])) {
                    $j++;
                    $count = $count + $j;
                    $data[$count] = $v;
                    $ping = 1;
                    $this->assign('ping', $ping);

                }
            }
        }

        //错误信息
        $arr = '';
        $class_all = '';
        $pre_class_ids_all = Db::name('class_student')->where(['old_class_id' => $id])->find();
        $pre_class_ids = $pre_class_ids_all['pre_class_ids'];
        $pre_class_ids = explode(',', $pre_class_ids);
        //如果原班也续班了，那么就不可选了
        $data_old = Db::name('class')->alias('c')->field(['is_and_class', 'name', 'id'])
            ->where(['c.id' => ['in', $pre_class_ids]])->select();
        foreach ($data_old as $k => $v) {
            if ($v['is_and_class'] == 1) {
                $arr .= $v['name'] . '--班级已经并到别的班级了';
            } else {
                $class_all[$k]['name'] = $v['name'];
                $class_all[$k]['id'] = $v['id'];
            }

        }
//        查看回访信息-chase添加;
        $model = new StudentVisitModel();

        foreach ($data as &$x) {
            $tid = $x['tid'];
            $class_id = $x['class_id'];
            if (!empty($x['old_class_id'])) {
                $old_class_id = $x['old_class_id'];
            } else {
                $old_class_id = 0;
            }

            $is_and_class1 = Db::name('class')->alias('cs')->where('cs.id', $class_id)->value('is_and_class');
            if (!empty($is_and_class1)) {
                $visit = $model->where(['delete_time' => 0, 'student_id' => $tid, 'class_id' => $old_class_id])->order('id desc')->select()->toArray();
                $class_id = $old_class_id;
            } else {
                $visit = $model->where(['delete_time' => 0, 'student_id' => $tid, 'class_id' => $class_id])->order('id desc')->select()->toArray();
            }

            foreach ($visit as &$v) {
                $v['content'] = trim(htmlspecialchars_decode($v['content']), '');
//                $visit[$k]=$v;
            }
            $x['visit'] = $visit;
        }

        if(!empty($arr))
        {
            $this->assign('arr', $arr);
        }
        $this->assign('id', $id);
        $this->assign('class_name', $class_name);
        $this->assign('class_all', $class_all);
        $this->assign('is_and_class', $is_and_class);
        $this->assign('data', $data);
        return $this->fetch();

    }

    /*
   * 预选班级
   */
    public function pre_class()
    {
        $param = $this->request->param();
        $id = $param['ids'];
        //错误信息
        $arr = '';
        $pre_class_ids = Db::name('class_student')->alias('cs')->where(['id' => $id, 'status' => 1])->value('cs.pre_class_ids');
        $pre_class_ids = explode(',', $pre_class_ids);
        //如果原班也续班了，那么就不可选了
        $data_old = Db::name('class')->alias('c')->field('is_and_class')
            ->where(['c.id' => ['in', $pre_class_ids]])->select();
        foreach ($data_old as $k => $v) {
            if ($v['is_and_class'] == 1) {
                $arr = $v['is_and_class'] . '班级已经并到别的班级了';
                unset($pre_class_ids[$k]);
            };
        }
        $data = Db::name('class')->alias('c')->field('c.id,c.name')
            ->where(['c.id' => ['in', $pre_class_ids]])->select();
        $this->assign('arr', $arr);
        return $data;
    }

    /*
  * 后台给学生选班
  */
    public function insert_class()
    {

        $param = $this->request->param();
        $data = $this->request->post();
        dump($data);
        $select = $data['select']; //出过来的班级


        if (empty($data['select'])) {
            $this->error('至少选中一个班级');
        }
        $school_name = Db::name('class')->where(['id' => $data['select']])->value('name');

        $student_ids = [];
        $student_name = '';

        //如果分班,但是并班的人数+现有班级人数小于现有能容纳的人数
        $class_data = Db::name('class')->where(['id' => $data['select']])->find();
        $current_num=$class_data['current_num'];
        $total_num=$class_data['total_num'];
        $fen_total = count($data['ids']) + intval($current_num);
        if($total_num<$fen_total)
        {
            $this->error('超过此班级最大容纳人数');
        }

        Db::startTrans();
        try {
            foreach ($data['ids'] as $k => $v) {
                Db::name('class_student')->where(['id' => $v])->update(['class_id' => $select, 'insert_class_time' => time()]);
                $student_ids[] = Db::name('class_student')->where(['id' => $v])->value('student_id');
            }
            $current_num = Db::name('class_student')->where(['class_id' => $data['select']])->where('status',0)
                ->where('student_id', '<>', 0)->count(); //改变班级人数
            $current_num = count($data['ids']) + intval($current_num);
            Db::name('class')->where(['id' => $data['select']])->update(['current_num' => $current_num]);


            foreach ($student_ids as $k => $v) {
                $student_name .= Db::name('student')->where(['id' => $v])->value('name') . ', ';
            }
            Db::commit();
            //记录日志
            $ids = implode(',', $student_ids);
            $pk = $ids; //主键
            $table = 'class';//数据表名
            $content = lang('DISTRIBUTE_STUDENT', ['name' => $student_name, 'class' => $school_name]);
            do_log($content, $pk, $table, time());
            $this->success('分班成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error('分班失败');
        }


    }

    /*
      * *查询班级
     */
    public function search_class()
    {
        $id = $this->request->param('id');
        $classmodel = new ClassModel();
        $class_data = $classmodel->where(['school_id' => $id, 'delete_time' => 0])->select()->toArray();
        return json_encode($class_data);
    }

    /*
     * add查询的续班的同校区同班级
     */
    public function searchxu()
    {
        $course_id = $this->request->param('course_id');
        $school_id = $this->request->param('school_id');

        //续班的班级 续班的班级不能是并班的，续班的班级是没有开课的或者此版开始时间大于此版的结束时间
        //找到此课程的，此校区的课程
        /*
             $class_data=Db::query('
            select * from cmf_class c JOIN
            (select max(date) mad,min(date) mid,class_id from cmf_course_schedule group by class_id
            HAVING min(date)>(select max(date) from cmf_course_schedule  where class_id=$last_id group by class_id )) as cc
            on c.id=cc.class_id where c.delete_time=0 and c.is_and_class=0 and c.class_status=0
             ');
            */

        $class_data = Db::name('class')->where(['delete_time' => 0, 'school_id' => $school_id, 'course_id' => $course_id, 'is_and_class' => 0, 'class_status' => 0])->select()->toArray();


        return json_encode($class_data);

    }

    /**
     * @return \think\response\Json
     */
    public function ajax1_class()
    {
        $param=$this->request->param();
        $course_id = $this->request->param('course_id');
        $school_id = $this->request->param('school_id');
        //$course_id,$school_id为空的
        if (empty($param['school_id']) && empty($param['course_id'])) {
            $json_data = [
                'code' => 0,
                'msg' => '校区ID不能为空',
                'data' => []
            ];
            return json_encode($json_data);
        }
        //course_id为空，school_id不为空
        if (!empty($param['school_id']) && empty($param['course_id'])) {
//            $data = Db::name('class')->where(['delete_time' => 0, 'is_class '=>1,'school_id' => $school_id])->select();
            $data=[];
        }
        //school_id为空，$course_id为空
        if (empty($param['school_id']) && !empty($param['course_id'])) {
//            $data = Db::name('class')->where(['delete_time' => 0, 'course_id' => $course_id,'is_class '=>1])->select();
            $data=[];

        }
        //school_id和$course_id不为空
        if (!empty($param['school_id']) && !empty($param['course_id'])) {
          /*
            $data = Db::name('class')->alias('c')->field('c.*')
                ->join('order o','o.class_id=c.id')
                ->where(['c.delete_time' => 0,'c.is_class '=>1,'c.school_id' => $school_id, 'c.course_id' => $course_id])
                ->where('o.order_status', ['eq', 2], ['eq', 1], 'or')
                ->select();
          */
            $data = Db::name('class')->alias('c')->
            field('c.*')
                ->join('school sc', 'c.school_id=sc.id')
                ->join('course co', 'c.course_id=co.id')
                ->where(['c.delete_time' => 0,'c.is_class '=>1,'c.is_and_class'=>0,'c.school_id' => $school_id, 'c.course_id' => $course_id, 'c.shop_id' => $this->admin_shop_id])
                ->select();
        }
            if (count($data)<1) {
                $json_data = [
                    'code' => 0,
                    'msg' => '没有更多数据',
                    'school_id' => $param['school_id'],
                    'data' => $data
                ];
                return json_encode($json_data);
            }
            $json_data = [
                'code' => 1,
                'msg' => 'success',
                'school_id' => $param['school_id'],
                'course_id'=>$param['course_id'],
                'data' => $data
            ];
            return json_encode($json_data);
    }

    /*
    * *查询教室
   */

    public function search()
    {
        $id = $this->request->param('id');
        $classmodel = new ClassroomModel();
        $class_data = $classmodel->where(['school_id' => $id, 'delete_time' => 0])->select()->toArray();
        return json_encode($class_data);
    }
    /*
  * ajax生成教室模板
  */
    public function classroom($id)
    {

        if (empty($id)) {
            $this->error('参数为空');
        }
        $model = new ClassroomModel();
        $data = $model->where('id', $id)->find();
        if (empty($data->id)) {
            $this->error('没有该教室信息', 'classroom/index');
        }
        if (!empty($data->vip)) {
            $data->vip = unserialize($data->vip);
        }
        if (!empty($data->aisle)) {
            $data->aisle = unserialize($data->aisle);
        }

        $this->assign('data', $data);
        return $data;

    }

    /*
     * ajax生成教室模板和学生对应的座位数
     */
    public function classroom_student()
    {

        $param = $this->request->param();
        $id = $param['id'];
        $class_id = $param['class_id'];
        $model = new ClassroomModel();
        $seat_model = new ClassSeatModel();
        $data = $model->where('id', $id)->find();
        $reserved_seats = $seat_model->where(['classes_id' => $class_id, 'delete_time' => 0, 'student_id' => 0])->find();
        $data_seat = $seat_model->where(['classes_id' => $class_id, 'delete_time' => 0])->where('student_id', '<>', '0')->select()->toArray();
        $student = new StudentModel();
        foreach ($data_seat as $k => $v) {
            $student_id = $v['student_id'];
            if (!empty($v['student_seat'])) {
                $seat = unserialize($v['student_seat']);
                $student_name = $student->where(['id' => $student_id])->value('name');
                $data[$student_name] = $seat;
            }
        }
//        return ($data_seat->reserved_seats);
        //判断的保留座位
        if (!empty($reserved_seats->reserved_seats)) {
            $data->reserved_seats = unserialize($reserved_seats->reserved_seats);
        } else {
            $data->reserved_seats = '';
        }
        //判断的学生信息
        if (!empty($data_seat->student_seat)) {
            $data->student_seat = unserialize($data_seat->student_seat);
        } else {
            $data->student_seat = '';
        }
        if (empty($data->id)) {
            $this->error('没有该教室信息', 'classroom/index');
        }
        if (!empty($data->vip)) {
            $data->vip = unserialize($data->vip);
        }
        if (!empty($data->aisle)) {
            $data->aisle = unserialize($data->aisle);
        }

        $this->assign('data', $data);
        return $data;

    }

    /**
     * 学生请假列表
     * @return mixed
     */
    public function student_leave()
    {
        $param = $this->request->param();
        $limit = config('limit_per_page');
        $classes = [];
        $where = [];
        //店铺ID
        $where['st.shop_id'] = ['=', $this->admin_shop_id];

        //TODO(steven):权限限制
        $uid = cmf_get_current_admin_id();
        $class_mdl = new ClassModel();
        $roles = $class_mdl->roleAuth($uid, $this->admin_shop_id);
        if (count($roles) > 0) {
            foreach ($roles as $v) {
                if ($v['name'] == '教师') {
                    $where['sl.teacher_id'] = ['=', $uid];
                    break;
                }
            }
        }

        if (!empty($param['school_id']) && is_numeric($param['school_id'])) {
            //学校
            $where['sl.school_id'] = intval($param['school_id']);
            //获取班级
            $class = Db::name('class')
                ->where('shop_id', '=', $this->admin_shop_id)
                ->where('delete_time', '=', 0)
                ->where('school_id', '=', intval($param['school_id']))
                ->field('id,name')
                ->select();
            if (!$class->isEmpty()) {
                $classes = $class;
            }

            if (!empty($param['class_id']) && is_numeric($param['class_id'])) {
                //班级
                $where['sl.class_id'] = intval($param['class_id']);
            }
        }

        if (!empty($param['course_id']) && intval($param['course_id']) != -1) {
            //课程
            $where['sl.course_id'] = intval($param['course_id']);
        }

        if (isset($param['change_course']) && intval($param['change_course']) != -1) {
            //调课状态
            $where['sl.change_course'] = intval($param['change_course']);
        }

        if (!empty($param['start']) && !empty($param['end'])) {
            //请假上课时间
            $start = strtotime($param['start']);
            $end = strtotime($param['end']);
            $where['sl.date'] = [['>= time', $start], ['<= time', $end]];
        } else {
            if (!empty($param['start'])) {
                $where['sl.date'] = ['>= time', strtotime($param['start'])];
            }
            if (!empty($param['end'])) {
                $where['sl.date'] = ['<= time', strtotime($param['end'])];
            }
        }

        $page_query = [
            'school_id' => isset($param['school_id']) ? $param['school_id'] : '',
            'class_id' => isset($param['class_id']) ? $param['class_id'] : '',
            'course_id' => isset($param['course_id']) ? $param['course_id'] : '',
            'change_course' => isset($param['change_course']) ? $param['change_course'] : '-1',
            'start' => isset($param['start']) ? $param['start'] : '',
            'end' => isset($param['end']) ? $param['end'] : '',
        ];

        $leave_model = new StudentLeaveModel();
        $data = $leave_model->getLeave($where, [], $limit, $page_query);

        //获取学校
        $school_mdl = new SchoolModel();
        $school = $school_mdl->getAllSchool($this->admin_shop_id);
        //获取课程
        $course_mdl = new CourseModel();
        $courses = $course_mdl->getAllCourse($this->admin_shop_id);

        $this->assign('param', $param);
        $this->assign('leaves', $data);
        $this->assign('campus', $school);
        $this->assign('classes', $classes);
        $this->assign('course', $courses);
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    /**
     * @return \think\response\Json
     */
    public function ajax_class()
    {
        if ($this->request->isPost()) {
            $param = $this->request->post();
            if (empty($param['school_id'])) {
                $json_data = [
                    'code' => 0,
                    'msg' => '校区ID不能为空',
                    'data' => []
                ];
                return json($json_data);
            }
            $data = Db::name('class')->where('delete_time', '=', 0)
                ->where('school_id', '=', intval($param['school_id']))
                ->field('id,name')->select();

            if ($data->isEmpty()) {
                $json_data = [
                    'code' => 0,
                    'msg' => '没有更多数据',
                    'school_id' => $param['school_id'],
                    'data' => $data
                ];
                return json($json_data);
            }

            $json_data = [
                'code' => 1,
                'msg' => 'success',
                'school_id' => $param['school_id'],
                'data' => $data
            ];
            return json($json_data);
        }
    }

    /*
     * 学生请假处理补课
     */
    public function handle_leave()
    {
        $cur_time = time();
        $table = 'student_leave';
        $leave_mdl = new StudentLeaveModel();

        $param = $this->request->param();
        $pk = $param['id'];
        if (isset($param['id']) && is_numeric($param['id'])) {
            $id = $this->request->param('id', 0, 'intval');
            //获取请假信息
            $leave = $leave_mdl->alias('sl')
                ->field('sl.*,s.name as student_name')
                ->join('student s','sl.student_id=s.id')
                ->where('sl.id','eq',$id)
                ->find();
            if(count($leave) <= 0){
                $this->error('没有该请假');
            }

            $status = $this->request->param('change_course');
            if (trim($status) == 'y') {
                //批准
                $handle = 1;
                $log_handle = '批准';

                //保存录音
                $adjust_data = [
                    'type' => 1,//录音
                    'leave_id' => $leave['id'],
                    'student_id' => $leave['student_id'],
                    'old_school_id' => $leave['school_id'],
                    'old_class_id' => $leave['class_id'],
                    'schedule' => $leave['schedule'],
                    'create_time' => $cur_time,
                ];
                Db::name('student_adjust')->insert($adjust_data);

                //更新请假信息
                $leave_data = [
                    'change_course' => 1,
                    'status' => 1,
                ];
                Db::name('student_leave')->where(['id'=>$id])->update($leave_data);

            }else{
                //拒绝
                $handle = 2;
                $log_handle = '拒绝';
            }

            //修改状态
            $leave_mdl->where(['id' => $id])->update(['status' => $handle, 'update_time' => $cur_time]);

            //记录日志
            $content = lang('HANDLE_STUDENT_LEAVE', ['handle'=>$log_handle, 'name'=>$leave['student_name']]);
            do_log($content, $pk, $table, $cur_time);

            $this->success("操作成功！");
        } else {
            $this->error('操作失败！');
        }

    }

    /**
     * 通过班级筛选排课课时
     * @return \think\response\Json
     */
    public function ajax_schedule()
    {
        $param = $this->request->post();

        if (empty($param['class_id'])) {
            $json_data = [
                'code' => 0,
                'msg' => '班级不能为空',
                'data' => []
            ];
            return json($json_data);
        }

        //获取班级
        $schedule = Db::name('course_schedule')->alias('cs')
            ->field('cs.*,FROM_UNIXTIME(cs.date, "%Y-%m-%d") as date_time')
            ->where('cs.class_id', 'eq', $param['class_id'])
            ->where('cs.date', 'gt', time())//当前时间以后的课时
            ->select();
        if (count($schedule) <= 0) {
            $json_data = [
                'code' => 0,
                'msg' => '没有更多数据',
                'class_id' => $param['class_id'],
                'data' => []
            ];
            return json($json_data);

        } else {
            $json_data = [
                'code' => 1,
                'msg' => 'success',
                'class_id' => $param['class_id'],
                'data' => $schedule
            ];
            return json($json_data);
        }
    }

    /**
     * 给请假学生调课
     * @return \think\response\Json
     */
    public function adjustSchedule()
    {
        $cur_time = time();
        $param = $this->request->post();
        if (empty($param['leave_id']) || empty($param['adjust_school_id']) || empty($param['adjust_class_id']) || empty($param['adjust_course_time'])
            || empty($param['old_school_id']) || empty($param['old_class_id']) || empty($param['student_id'])
        ) {
            $json_data = [
                'Message' => '请求数据不能为空',
                'Status' => 0,
            ];
            return json($json_data);
        }

        //课时
        $adjust_course_time = explode(',', $param['adjust_course_time']);
        if (count($adjust_course_time) < 2) {
            $json_data = [
                'Message' => '请求课时错误',
                'Status' => 0,
            ];
            return json($json_data);

        }
        $data['schedule_id'] = $adjust_course_time[0];//排课
        $data['schedule'] = $adjust_course_time[1];//课程进度

        $data['create_time'] = $cur_time;
        $data['type'] = 2;//申请调课
        $data['leave_id'] = $param['leave_id'];//请假id
        $data['student_id'] = $param['student_id'];
        $data['school_id'] = $param['adjust_school_id'];
        $data['class_id'] = $param['adjust_class_id'];

        $data['old_school_id'] = $param['old_school_id'];
        $data['old_class_id'] = $param['old_class_id'];

        if ($data['old_school_id'] == $data['school_id'] && $data['old_class_id'] == $data['class_id']) {
            $json_data = [
                'Message' => '不可调到同一个班级',
                'Status' => 0,
            ];
            return json($json_data);
        }

        //排课信息(如果是加课就根据排课ID检索)
        if (empty($data['schedule'])) {
            //是加课
            $condition['id'] = $data['schedule_id'];
        } else {
            $condition['schedule'] = $data['schedule'];
        }
        $condition['class_id'] = $data['class_id'];
        $course_schedule = Db::name('course_schedule')->where($condition)->find();

        //判断是否和请假的信息一样
        $leave_mdl = new StudentLeaveModel();
        $res = $leave_mdl->where('student_id', '=', $data['student_id'])
            ->where('school_id', '=', $data['school_id'])
            ->where('class_id', '=', $data['class_id'])
            ->where('date', '=', $course_schedule['date'])
            ->where('start_time', '=', $course_schedule['start_time'])
            ->where('end_time', '=', $course_schedule['end_time'])
            ->where('schedule', '=', $course_schedule['schedule'])
            ->find();
        if (count($res) > 0) {
            $json_data = [
                'Message' => '所选信息已在请假列表，请重新调课',
                'Status' => 0,
            ];
            return json($json_data);

        } else {
            //学生请假调课模型
            $adjust_mdl = new StudentAdjustModel();
            $adjust_data = $adjust_mdl->where('leave_id', 'eq', $data['leave_id'])->find();
            if (isset($adjust_data['id'])) {
                /********更新调课***********/
                $data['update_time'] = $cur_time;
                $adjust_mdl->isUpdate(true)->allowField(true)->save($data, ['leave_id' => $data['leave_id']]);

                //发送站内通知
                $this->sendAdjustMsg($adjust_data['id']);

            } else {
                /********新增调课***********/

                //保存调课信息
                $id = $adjust_mdl->insertGetId($data);
                if ($id) {
                    //发送站内通知
                    $this->sendAdjustMsg($id);

                } else {
                    $json_data = [
                        'Message' => '调课失败',
                        'Status' => 0,
                    ];
                    return json($json_data);
                }
            }
            //调课成功
            $leave_data = [
                'change_course' => 2,
                'status' => 1,
            ];
            Db::name('student_leave')->where(['id'=>$data['leave_id']])->update($leave_data);
            //记录日志
            $student = Db::name('student')->find($data['student_id']);
            $content = lang('HANDLE_STUDENT_LEAVE', ['handle'=>'批准', 'name'=>$student['name']]);
            do_log($content, $data['leave_id'], 'student_leave,student_adjust', $cur_time);

            $json_data = [
                'Message' => '调课成功',
                'Status' => 1,
            ];
            return json($json_data);
        }
    }

    /**
     * 学生请假调课后发送站内信
     * @param $id
     * @return bool
     */
    public function sendAdjustMsg($id)
    {
        if (empty($id) || !is_numeric($id)) {
            return false;
        }
        $adjust_where['sa.id'] = $id;
        $adjust_mdl = new StudentAdjustModel();
        //获取学生请假调课信息
        $adjust_data = $adjust_mdl->getAdjustByField($adjust_where);
        if (count($adjust_data) <= 0) {
            return false;
        }
        //课时
        $course_time = date('Y-m-d', $adjust_data['date']) . ' ' . $adjust_data['start_time'] . '~' . $adjust_data['end_time'] . ' ' . $adjust_data['week'];
        $content = lang('ADJUST_SCHEDULE', ['name' => $adjust_data['student_name'], 'school' => $adjust_data['school_name'], 'class' => $adjust_data['class_name'], 'courseTime' => $course_time]);

        //获取学生
        $student = Db::name('student')->find($adjust_data['student_id']);
        //消息信息
        $result['shop_id'] = $this->admin_shop_id;
        $result['subject'] = '请假补课';
        $result['content'] = $content;
        $result['type'] = 0;//站内通知
        $result['send_uid'] = cmf_get_current_admin_id();
        $result['create_time'] = time();
        $ids[] = ['id' => $student['u_id']];

        $msg_mdl = new MessageModel();
        $res = $msg_mdl->sendMsg($result, $ids);
        if ($res) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取学生调课列表
     * @return \think\response\Json
     */
    public function ajax_adjust_list()
    {
        $param = $this->request->post();

        if (empty($param['student_id']) || empty($param['school_id']) || empty($param['class_id'])) {
            $json_data = [
                'code' => 0,
                'msg' => '请求参数不能为空',
                'data' => []
            ];
            return json($json_data);
        }

        $condition = [
            'sa.student_id' => $param['student_id'],
            'sa.old_school_id' => $param['school_id'],
            'sa.old_class_id' => $param['class_id'],
        ];
        //获取调课信息
        $adjust_mdl = new StudentAdjustModel();
        $adjust_data = $adjust_mdl->alias('sa')
            ->field('sa.*,sc.name as school_name,cl.name as class_name,st.name as student_name,co.course_name,co.course_hour')
            ->join('school sc', 'sa.school_id=sc.id')
            ->join('class cl', 'sa.class_id=cl.id')
            ->join('student st', 'sa.student_id=st.id')
            ->join('course co', 'cl.course_id=co.id')
            ->where($condition)
            ->select();
        if (count($adjust_data) <= 0) {
            $json_data = [
                'code' => 0,
                'msg' => '没有更多数据',
                'data' => []
            ];
            return json($json_data);

        } else {
            //获取排课
            $adjust_data = $adjust_data->toArray();
            foreach ($adjust_data as $k => $v) {
                if ($v['schedule'] == 0) {
                    //是临时加课
                    $where['id'] = $v['schedule_id'];
                } else {
                    $where['schedule'] = $v['schedule'];
                }
                $where['class_id'] = $v['class_id'];

                $schedule_mdl = new CourseScheduleModel();
                $course_schedule = $schedule_mdl->where($where)->find();
                if (count($course_schedule) <= 0) {
                    unset($adjust_data[$k]);
                    continue;
                } else {
                    $new_data = [
                        'date' => date('Y-m-d', $course_schedule['date']),
                        'start_time' => $course_schedule['start_time'],
                        'end_time' => $course_schedule['end_time'],
                        'week' => $course_schedule['week'],
                        'delete_url' => url('Classes/deleteAdjust', ['id' => $v['id']], true, true),
                    ];
                    $adjust_data[$k] = array_merge($v, $new_data);
                }
            }

            $json_data = [
                'code' => 1,
                'msg' => 'success',
                'data' => $adjust_data
            ];
            return json($json_data);
        }
    }

    /**
     *删除调课
     */
    public function deleteAdjust()
    {
        $cur_time = time();
        $table = 'student_adjust';
        $adjust_mdl = new StudentAdjustModel();

        $param = $this->request->param();
        $id = $param['id'];
        if (empty($id)) {
            $this->error('参数为空，删除失败',null,'',1);
        }
        //记录日志
        $pk = $id;
        $adjust_where['sa.id'] = $id;
        //获取调课信息
        $adjust_data = $adjust_mdl->getAdjustByField($adjust_where);

        //删除调课
        $result = $adjust_mdl->deleteAdjust($id, $cur_time);
        if ($result) {
            //更改信息
            $leave_data = [
                'change_course' => 2,
                'status' => 0,
            ];
            Db::name('student_leave')->where(['id'=>$adjust_data['leave_id']])->update($leave_data);

            //课时
            $course_time = date('Y-m-d', $adjust_data['date']) . ' ' . $adjust_data['start_time'] . '~' . $adjust_data['end_time'] . ' ' . $adjust_data['week'];
            $content = lang('DELETE_SCHEDULE', ['name' => $adjust_data['student_name'], 'school' => $adjust_data['school_name'], 'class' => $adjust_data['class_name'], 'courseTime' => $course_time]);
            do_log($content, $pk, $table, $cur_time);

            $this->success("删除成功！",null,'',1);
        } else {
            $this->error('删除失败！',null,'',1);
        }
    }

    /**
     * 试听列表
     * @param request
     * @return mixed
     */
    public function audition()
    {
        $param = $this->request->param();
        $limit = config('limit_per_page');
        $classes = [];

        $where = [
            'a.shop_id' => ['=', $this->admin_shop_id],
        ];

        if (!empty($param['school_id']) && is_numeric($param['school_id'])) {
            //学校
            $where['a.school_id'] = intval($param['school_id']);
            //获取班级
            $class = Db::name('class')
                ->where('shop_id', '=', $this->admin_shop_id)
                ->where('delete_time', '=', 0)
                ->where('school_id', '=', intval($param['school_id']))
                ->field('id,name')
                ->select();
            if (!$class->isEmpty()) {
                $classes = $class;
            }

            if (!empty($param['class_id']) && is_numeric($param['class_id'])) {
                //班级
                $where['a.class_id'] = intval($param['class_id']);
            }
        }

        if (!empty($param['course_id']) && intval($param['course_id']) != -1) {
            //课程
            $where['a.course_id'] = intval($param['course_id']);
        }

        if (isset($param['status']) && intval($param['status']) != -1) {
            //状态
            $where['a.status'] = intval($param['status']);
        }

        if (!empty($param['start']) && !empty($param['end'])) {
            //上课时间
            $start = strtotime($param['start']);
            $end = strtotime($param['end']);
            $where['a.date'] = [['>= time', $start], ['<= time', $end]];
        } else {
            if (!empty($param['start'])) {
                $where['a.date'] = ['>= time', strtotime($param['start'])];
            }
            if (!empty($param['end'])) {
                $where['a.date'] = ['<= time', strtotime($param['end'])];
            }
        }

        $page_query['query'] = [
            'school_id' => isset($param['school_id']) ? $param['school_id'] : '',
            'class_id' => isset($param['class_id']) ? $param['class_id'] : '',
            'course_id' => isset($param['course_id']) ? $param['course_id'] : '',
            'status' => isset($param['status']) ? $param['status'] : '',
            'start' => isset($param['start']) ? $param['start'] : '',
            'end' => isset($param['end']) ? $param['end'] : '',
        ];

        $listen_mdl = new AuditionModel();
        $data = $listen_mdl->alias('a')
            ->field('a.*,sc.name as school_name,cl.name as class_name,co.course_name,st.name as student_name,
            u.mobile,u.user_login as parent_name')
            ->join('school sc', 'a.school_id=sc.id')
            ->join('student st', 'a.student_id=st.id')
            ->join('user u', 'a.parent_id=u.id')
            ->join('class cl', 'a.class_id=cl.id')
            ->join('course co', 'a.course_id=co.id')
            ->where($where)->order('a.id', 'desc')
            ->paginate($limit, false, $page_query);

        //获取学校
        $school_mdl = new SchoolModel();
        $school = $school_mdl->getAllSchool($this->admin_shop_id);
        //获取课程
        $course_mdl = new CourseModel();
        $courses = $course_mdl->getAllCourse($this->admin_shop_id);

        $this->assign('param', $param);
        $this->assign('listen', $data);
        $this->assign('schools', $school);
        $this->assign('classes', $classes);
        $this->assign('course', $courses);
        $this->assign('page', $data->render());
        return $this->fetch();
    }

    /*
     * 安排试听
     */
    public function handle_audition()
    {
        $cur_time = time();
        $table = 'audition';
        $listen_mdl = new AuditionModel();

        $param = $this->request->param();
        $pk = $param['id'];

        if (isset($param['id']) && is_numeric($param['id'])) {
            $id = $this->request->param('id', 0, 'intval');
            $status = $this->request->param('status');
            if ($status == 'y') {
                //插班
                $handle = 1;
                $log_handle = '插班-允许';
            } else{
                //释放
                $handle = 2;
                $log_handle = '释放-结束';
            }

            //获取试听信息
            $audition = $listen_mdl->alias('a')
                ->field('a.*,s.name as student_name')
                ->join('student s','a.student_id=s.id')
                ->where('a.id','eq',$id)
                ->find();
            if(count($audition) <= 0){
                $this->error('没有该试听信息');
            }

            //开启事务
            Db::startTrans();
            try {
                $listen_mdl->where(['id' => $id])->update(['status' => $handle, 'update_time' => $cur_time]);
                //释放座位
                if ($handle == 2) {
                    $table = 'audition,class_seat,class_student,class,order';

                    //修改订单状态(2:已完成)
                    Db::name('order')->where(['id'=>$audition['order_id']])->update(['order_status'=>2]);

                    $class_mdl = new ClassModel();
                    $res = $class_mdl->releaseSeat($audition['class_id'], $audition['student_id'], $this->admin_shop_id);
                    if(!$res){
                        //手动抛出异常
                        \exception('释放座位失败');
                    }
                }
                Db::commit();

            } catch (Exception $e) {
                Db::rollback();
                $this->error('操作失败！');
            }

            if($handle == 1){
                //发送站内通知
                $this->sendAuditionMsg($id);
            }

            //记录日志
            $content = lang('HANDLE_AUDITION', ['handle'=>$log_handle, 'name'=>$audition['student_name']]);
            do_log($content, $pk, $table, $cur_time);

            $this->success("操作成功！");

        } else {
            $this->error('操作失败！');
        }
    }

    /**
     * 安排试听发送站内信
     * @param $id
     * @return bool
     */
    public function sendAuditionMsg($id)
    {
        if (empty($id) || !is_numeric($id)) {
            return false;
        }
        $where['a.id'] = $id;
        $audition_mdl = new AuditionModel();
        //获取试听信息
        $data = $audition_mdl->getAuditionByField($where);
        if (count($data) <= 0) {
            return false;
        }
        //课时
        $course_time = date('Y-m-d', $data['date']) . ' ' . $data['start_time'] . '~' . $data['end_time'] . ' ' . $data['week'];
        $content = lang('AUDITION', ['name' => $data['student_name'], 'school' => $data['school_name'], 'class' => $data['class_name'], 'courseTime' => $course_time]);

        //消息信息
        $result = [
            'shop_id' => $this->admin_shop_id,
            'subject' => '试听课',
            'content' => $content,
            'type' => 0,//站内通知
            'send_uid' => cmf_get_current_admin_id(),
            'create_time' => time(),
        ];
        $ids[] = ['id' => $data['parent_id']];

        $msg_mdl = new MessageModel();
        $res = $msg_mdl->sendMsg($result, $ids);
        if ($res) {
            return true;
        } else {
            return false;
        }
    }

    //导出excel
    public function excel()
    {
        import('phpexcel.PHPExcel', EXTEND_PATH);
        import('phpexcel.PHPExcel.IOFactory', EXTEND_PATH);
        import('phpexcel.PHPExcel.Shared',EXTEND_PATH);
        $objPHPExcel = new PHPExcel();
        //查出所有数据
        $class_data = new ClassModel();
        $id = $this->request->param('id');
        $num = $this->request->param('num1');
        if(empty($num))
        {
            $this->error('请输入第几次回访');
        }
        $param = $this->request->param();
//        var_dump($param);
//        exit();
        $is_and_class = Db::name('class')->alias('cs')->where('cs.id', $id)->value('is_and_class');
        $class_name = Db::name('class')->alias('cs')->where('cs.id', $id)->value('name');
        if (!empty($is_and_class)) {
            $subsql = Db::table('cmf_student_visit')->where(['delete_time' => 0, 'num' => $num])->field('*')->buildSql();

            //没有并班的详情页
            $data = Db::name('class_student')->alias('cs')->field('t.id tid,t.birthday,t.school_name,t.code tcode,t.grade tgrade,t.name tname,t.gender tgender,t.parent_name,t.mobile,cs.id,cs.status,cs.insert_class_time,cs.old_class_id,cs.class_id,cs.pre_class_ids,c.name cname,s.content')
                ->join('class c', 'c.id=cs.class_id')
                ->join('student t', 't.id=cs.student_id')
                ->join([$subsql => 's'], 's.student_id=t.id and s.class_id=c.id', $type = 'left')
                ->where('cs.old_class_id', $id)
                ->order("convert(`tname` USING gbk) COLLATE gbk_chinese_ci")
                ->select();
        } else {
            $subsql = Db::table('cmf_student_visit')->where(['delete_time' => 0, 'num' => $num])->field('*')->buildSql();
            //没有并班的详情页
            $data = Db::name('class_student')->alias('cs')->field('t.id tid,t.code tcode,t.birthday,t.school_name,t.grade tgrade,t.name tname,t.gender tgender,t.parent_name,t.mobile,cs.id,cs.insert_class_time ,cs.status,cs.old_class_id,cs.class_id,cs.id,cs.pre_class_ids,c.name cname,s.content')
                ->join('class c', 'c.id=cs.class_id')
                ->join('student t', 't.id=cs.student_id')
                ->where(['cs.class_id' => $id])
                ->join([$subsql => 's'], 's.student_id=t.id and s.class_id=c.id', $type = 'left')
                ->where(['c.is_and_class' => 0])
                ->order("convert(`tname` USING gbk) COLLATE gbk_chinese_ci")
                ->select();
        }
        $objSheet = $objPHPExcel->getActiveSheet();//获取当前活动sheet
        $objSheet->setTitle("班级的的学生访问表");//给当前活动sheet起个名称
        // Set properties
        $objPHPExcel->getProperties()->setCreator("ctos")
            ->setLastModifiedBy("ctos")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");

        //设置列宽
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(35);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(35);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(35);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(35);

        $objPHPExcel->getActiveSheet()->getStyle('A1:M1')->getFont()->setSize(14)->setBold(true);
        $objPHPExcel->getActiveSheet()->getStyle('A2:M220')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        $objSheet->setCellValue("A1", "姓名")->setCellValue("B1", "学号")->setCellValue("C1", "性别")
            ->setCellValue("D1", "年级")->setCellValue("E1", "班级")->setCellValue("F1", "手机号")
            ->setCellValue("G1", "回访内容")
            ->setCellValue("H1", "生日")
            ->setCellValue("I1", "学校")

        ;//填充数据
        $j = 2;
        //时间格式
        $phpexcel_date_format = array(\PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD, \PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2, \PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY, \PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYSLASH, \PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYMINUS, \PHPExcel_Style_NumberFormat::FORMAT_DATE_DMMINUS, \PHPExcel_Style_NumberFormat::FORMAT_DATE_MYMINUS, \PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME, \PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME1, \PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME2, \PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3, \PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4, \PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME5, \PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME6, \PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME7, \PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME8, \PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH, \PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14, \PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15, \PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX16, \PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX17, \PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX22);
        foreach ($data as $key => $val) {
            if ($val['tgender'] == 1) {
                $val['tgender'] = '男';
            } elseif ($val['tgender'] == 0) {
                $val['tgender'] = '保密';
            } else {
                $val['tgender'] = '女';
            }
            $objSheet->setCellValue("A" . $j, $val['tname'])->setCellValue("B" . $j, $val['tcode'])->setCellValue("C" . $j, $val['tgender'])
                ->setCellValue("D" . $j, $val['tgrade'])->setCellValue("E" . $j, $val['cname'])->setCellValue("F" . $j, $val['mobile'])
                ->setCellValue("G" . $j, $val['content'])
                ->setCellValue("H" . $j, $val['birthday'])
                ->setCellValue("I" . $j, $val['school_name']);
            $objSheet->setCellValue('H'.($j), \PHPExcel_Shared_Date::PHPToExcel($val['birthday']));
//            $objSheet->setCellValue('E'.($j), \PHPExcel_Shared_Date::PHPToExcel(time()));
            $objSheet->getStyle('H'.($j))->getNumberFormat()->setFormatCode($phpexcel_date_format[1]);
            $j++;

        }
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');//生成excel文件
        //$objWriter->save($dir."/export_1.xls");//保存文件

        // Set active sheet index to the first sheet
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();//清除缓冲区,避免乱码

        // Redirect output to a client’s web browser (Excel5)
        header('Content-Type: application/vnd.ms-excel');
        $filename = '班级导出' . '(' . date('Ymd-His') . ').xls';
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');


    }

    public function browser_export($type, $filename)
    {
        if ($type == "Excel5") {
            header('Content-Type: application/vnd.ms-excel');//告诉浏览器将要输出excel03文件
        } else {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器数据excel07文件
        }
        header('Content-Disposition: attachment;filename="' . $filename . '"');//告诉浏览器将输出文件的名称
        header('Cache-Control: max-age=0');//禁止缓存
    }

    public function addVisitPost()
    {

        $class_id = $this->request->param('class_id');
        $id = $this->request->param('id');

        $tid = $this->request->param('student_id');
        $old_class_id = Db::name('class_student')->alias('cs')->where('cs.class_id', $class_id)->value('old_class_id');
        $model = new StudentVisitModel();
        $post = $this->request->except('id');
        $post['create_time'] = time();
        $res = $model->insert($post);
        $tname = Db::name('student')->where(['id' => $tid])->value('name');
        if ($res) {
            $pk = $id; //主键
            $table = 'studentvisit';//数据表名
            $content = lang('ADD_STUDENT_VISIT', ['name' => $tname]);
            do_log($content, $pk, $table, time());
            $this->success('添加访问成功', url('classes/classes/view', array('id' => $id)));

        } else {
            $this->error('添加访问失败');
        }
    }

    public function deleteVisit()
    {

        $model = new StudentVisitModel();
        $id = $this->request->param('id');
        //开始事物
        Db::startTrans();
        try {
            $res = $model->where('id', intval($id))->update(['delete_time' => time()]);
            Db::commit();

            $student_id = $model->where('id', intval($id))->value('student_id');
            $tname = Db::name('student')->where(['id' => $student_id])->value('name');
            $pk = $id; //主键
            $table = 'studentvisit';//数据表名
            $content = lang('DELETE_STUDENT_VISIT', ['name' => $tname]);
            do_log($content, $pk, $table, time());

            $this->success('删除成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error('删除失败');
        }
    }


}
